<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/mes/mes/TechnologicalProcess.jsx或TechnologicalProcess.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="grid">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields"
            :searchFormOptions="searchFormOptions" :table="table" :extend="extend" :onInit="onInit" :onInited="onInited"
            :searchBefore="searchBefore" :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore"
            :rowClick="rowClick" :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter"
            :detailSortEnd="detailSortEnd">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>

        </view-grid>
    </div>
    <select-material ref="materialRef" @onSelectMaterial="onSelectMaterial"></select-material>
    <select-materialBom ref="materialBomRef" @onSelectMaterialBom="onSelectMaterialBom"></select-materialBom>
    <select-productProcess ref="productProcessRef"
        @onSelectProductProcess="onSelectProductProcess"></select-productProcess>
</template>
<script setup lang="jsx">
import extend from "@/extension/mes/mes/TechnologicalProcess.jsx";
import viewOptions from './TechnologicalProcess/options.js'
import SelectMaterial from './TechnologicalProcessSelectMaterial.vue'
import SelectMaterialBom from './TechnologicalProcessSelectMaterialBom.vue'
import SelectProductProcess from './TechnologicalProcessSelectProductProcess.vue'
import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())

let gridRef;//对应[表.jsx]文件中this.使用方式一样
const materialRef = ref();
const materialBomRef = ref();
const productProcessRef = ref();
//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;
    columns.forEach((x) => {
        if (x.field == 'ProductFile') {
            console.log(x)
            x.render = (h, { row, column, index }) => {
                //  percentage={90} 实际应该修改为：row.字段
                if (row.ProductFile != null) {

                    let list = row.ProductFile.split('/')
                    //90改为row.字段
                    let fieldValue = list[list.length - 1]
                    return <el-tag>{fieldValue}</el-tag>;
                }
                else {
                    return ""
                }
            };
        }
    });
    gridRef.details[0].sortable = true
    gridRef.details[0].pagination = {
        sortName: "ProcessSeq",
        order: "asc", //排序方式
    };
    const selectMaterialOption = gridRef.getFormOption("MaterialNo");
    selectMaterialOption.readonly = true;
    selectMaterialOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            materialRef.value.open();
        }
    };
    const selectMaterialBomOption = gridRef.getFormOption("BomNo");
    selectMaterialBomOption.readonly = true;
    selectMaterialBomOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            materialBomRef.value.open(editFormFields.MaterialId);
        }
    };

}
//选择物料
const onSelectMaterial = (rows) => {
    editFormFields.MaterialId = rows[0].MaterialId;
    editFormFields.MaterialNo = rows[0].Code;
    editFormFields.MaterialName = rows[0].Name;
    editFormFields.Spec = rows[0].Spec;
    editFormFields.Position = rows[0].Position;
    editFormFields.MaterialTypeId = rows[0].MaterialTypeId;

    gridRef.getTable("ProcessBomDetail").rowData = []

    //这里还可以给其他字段设置值editFormFields.字段=
    proxy.http.post('api/MaterialsBom/getBomByMaterialId', rows[0].MaterialId).then((result) => {
        if (result != null) {
            editFormFields.BomId = result.bomId
            editFormFields.BomNo = result.billNo
            editFormFields.BomVersion = result.bomVersion
            result.materialBomDetail.forEach(item => {
                gridRef.getTable("ProcessBomDetail").addRow({
                    NextBomId: item.nextBomId,
                    NextBomNo: item.nextBomNo,
                    MaterialId: item.materialId,
                    MaterialNo: item.materialNo,
                    MaterialName: item.materialName,
                    Spec: item.spec,
                    MaterialTypeId: item.materialTypeId,
                    Position: item.position,
                    DepartmentId: item.departmentId,
                    UnitQty: item.unitQty,
                    IsBackflush: item.isBackflush,
                    IsLot: item.isLot,
                    IsCriticalParts: item.isCriticalParts,
                    IsSpecialParts: item.isSpecialParts,
                    AttritionRate: item.attritionRate,
                    UnitId: item.unitId
                })
            })
        }else{
            editFormFields.BomId = null
            editFormFields.BomNo = null
            editFormFields.BomVersion = null
        }

    })

}
//选择Bom
const onSelectMaterialBom = (rows) => {
    editFormFields.MaterialId = rows[0].MaterialId;
    editFormFields.MaterialNo = rows[0].MaterialNo;
    editFormFields.MaterialName = rows[0].MaterialName;
    editFormFields.Spec = rows[0].Spec;
    editFormFields.Position = rows[0].Position;
    editFormFields.MaterialTypeId = rows[0].MaterialTypeId;

    gridRef.getTable("ProcessBomDetail").rowData = []

    //这里还可以给其他字段设置值editFormFields.字段=
    proxy.http.post('api/MaterialsBom/getBomByMaterialId', rows[0].MaterialId).then((result) => {
        editFormFields.BomId = result.bomId
        editFormFields.BomNo = result.billNo
        editFormFields.BomVersion = result.bomVersion

        result.materialBomDetail.forEach(item => {
            gridRef.getTable("ProcessBomDetail").addRow({
                NextBomId: item.nextBomId,
                NextBomNo: item.nextBomNo,
                MaterialId: item.materialId,
                MaterialNo: item.materialNo,
                MaterialName: item.materialName,
                Spec: item.spec,
                MaterialTypeId: item.materialTypeId,
                Position: item.position,
                DepartmentId: item.departmentName,
                UnitQty: item.unitQty,
                IsBackflush: item.isBackflush,
                IsLot: item.isLot,
                IsCriticalParts: item.isCriticalParts,
                IsSpecialParts: item.isSpecialParts,
                AttritionRate: item.attritionRate,
                UnitId: item.unitId
            })
        })
    })

}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    columns.forEach(x => {
        //开启表头过滤
        x.filterData = true;
    })
    
    //通过弹出框选择数据
    gridRef.details[0].buttons.unshift({
        name: '选择工序', //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        hidden: false, //是否隐藏按钮(如果想要隐藏按钮，在onInited方法中遍历buttons，设置hidden=true)
        onClick: () => {
            //触发事件
            productProcessRef.value.open()
        }
    })
    gridRef.details[0].columns.find(x => { return x.field == 'DepartmentId' }).multiple = false
    gridRef.details[1].columns.find(x => { return x.field == 'DepartmentId' }).multiple = false

    // 根据任务标准类型 锁定标准值单位
    details[0].columns.forEach(x => {
        if (x.field == 'SupplyId') {
            x.checkEdit = (row, column, index) => {
                if (row.IsOutSource == 0 || row.IsOutSource == null) {
                    //可根据row.字段的值返回true/false是否可以编辑
                    return false
                } else {
                    return true
                }
            }
        }
    })
}
//选择工序
const onSelectProductProcess = (rows) => {
    //转换数据格式与当前明细表字段一致
    rows = rows.map((c, index) => {

        return {

            ProductProcessId: c.ProductProcessId,
            ProcessCode: c.Code,
            ProcessName: c.Name,
            ProcessTypeId: c.ProcessTypeId,
            DeviceId: c.DeviceId,
            DepartmentId: c.DepartmentId,
            ProductionGroupId: c.GroupId,
            IsLasted: 0,
            IsOutSource: 0,
            ReportWorkTypeId: 1,
            IsDispatch: 0,
            ProcessSeq: index + 1,
            WorkHourPrice: c.WorkHourPrice,
            WorkQtyPrice: c.WorkQtyPrice,
            PriceTypeId: c.PriceTypeId,
            IsChecked: c.IsChecked,
        }
    })
    let rowData = gridRef.getTable('ProcessDetail').rowData
    //更新明细中最后一个行是否末级工序

    //写入明细表
    rowData.push(...rows)

    rowData.map((row, index) => {
        row.ProcessSeq = index + 1
        if (rowData.length == index + 1) {
            row.IsLasted = 1
        }
        else {
            row.IsLasted = 0
        }
    });
    // rowData.unshift(...rows)
}
const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询
    return true;
}
const searchAfter = async (rows, result) => {
    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const rowClick = ({ row, column, event }) => {
    //查询界面点击行事件
    // grid.value.toggleRowSelection(row); //单击行时选中当前行;
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
    if (gridRef.currentAction == 'Add') {
        gridRef.editFormFields.IsStricted = 0;
        gridRef.editFormFields.IsEnabled = 1;
    }
}
const detailSortEnd = (newIndex, rows, oldIndex) => {
    //拖动后对表的字段重新排序
    rows.forEach((x, index) => {
        if (rows.length == index + 1) {
            x.IsLasted = 1
        }
        else {
            x.IsLasted = 0
        }
        x.ProcessSeq = index + 1
    })
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
